Split linked list in parts¶
Time: O(N+K); Space: O(1); medium
Given a (singly) linked list with head node root, write a function to split the linked list into k consecutive linked list “parts”.
The length of each part should be as equal as possible: no two parts should have a size differing by more than 1. This may lead to some parts being null.
The parts should be in order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal parts occurring later.
Return a List of ListNode’s representing the linked list parts that are formed.
Example 1:
Input: root = {ListNode} 1->2->3->None, k = 5
Output: [{ListNode} 1->None, {ListNode} 2->None, {ListNode} 3->None, {ListNode} None, {ListNode} None]
Explanation:
The input and each element of the output are ListNodes, not arrays. For example, the input root has root.val = 1, root.next.val = 2, root.next.next.val = 3, and root.next.next.next = None. The first element output[0] has output[0].val = 1, output[0].next = None. The last element output[4] is null, but it’s string representation as a ListNode is [].
Example 2:
Input: root = {ListNode} 1->2->3->4->5->6->7->8->9->10->None, k = 3
Output: [ {ListNode} 1->2->3->4->None, {ListNode} 5->6->7->None, {ListNode} 8->9->10->None]
Explanation:
The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts.
Constraints:
The length of root will be in the range [0, 1000].
Each value of a node in the input will be an integer in the range [0, 999].
k will be an integer in the range [1, 50].
Hints:
If there are N nodes in the list, and k parts, then every part has N/k elements, except the first N%k parts have an extra one.
[16]:
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def __repr__(self):
if self:
return "{} -> {}".format(self.val, repr(self.next))
1. Create New Lists¶
Intuition and Algorithm
If there are N nodes in the linked list root, then there are N/k items in each part, plus the first N%k parts have an extra item. We can count N with a simple loop.
Now for each part, we have calculated how many nodes that part will have:
width + (i < remainder ? 1 : 0).
We create a new list and write the part to that list.
Our solution showcases constructs of the form a = b = c.
Note that this syntax behaves differently for different languages.
[17]:
class Solution1(object):
"""
Time: (N+K), where N is the number of nodes in the given list.
If k is large, it could still require creating many new empty lists.
Space: O(max(N,K)), the space used in writing the answer.
"""
def splitListToParts(self, root, k):
"""
:type root: ListNode
:type k: int
:rtype: List[ListNode]
"""
n = 0
curr = root
while curr:
curr = curr.next
n += 1
width, remainder = divmod(n, k)
result = []
curr = root
for i in range(k):
head = curr
for j in range(width-1+int(i < remainder)):
if curr:
curr = curr.next
if curr:
curr.next, curr = None, curr.next
result.append(head)
return result
[18]:
s = Solution1()
root = ListNode(1)
root.next = ListNode(2)
root.next.next = ListNode(3)
k = 5
res = s.splitListToParts(root, k)
# print(res) # ['1 -> None', '2 -> None', '3 -> None', None, None]
exp = [1,2,3,None,None]
i = 0
for val in exp:
if val:
assert res[i].val == val
res[i] = res[i].next
i += 1
root = ListNode(1)
root.next = ListNode(2)
root.next.next = ListNode(3)
root.next.next.next = ListNode(3)
root.next.next.next.next = ListNode(4)
root.next.next.next.next.next = ListNode(5)
root.next.next.next.next.next.next = ListNode(6)
root.next.next.next.next.next.next.next = ListNode(7)
root.next.next.next.next.next.next.next.next = ListNode(8)
root.next.next.next.next.next.next.next.next.next = ListNode(9)
root.next.next.next.next.next.next.next.next.next.next = ListNode(10)
k = 3
res = s.splitListToParts(root, k)
# print(res) # ['1 -> 2 -> 3 -> 3 -> None', '4 -> 5 -> 6 -> 7 -> None', '8 -> 9 -> 10 -> None']
exp = [[1,2,3,3], [4,5,6,7], [8,9,10]]
for grp in range(len(exp)):
for val in exp[grp]:
assert res[grp].val == val
res[grp] = res[grp].next
2. Split Input List¶
Intuition and Algorithm
As in Approach #1, we know the size of each part. Instead of creating new lists, we will split the input list directly and return a list of pointers to nodes in the original list as appropriate.
Our solution proceeds similarly. For a part of size L = width + (i < remainder ? 1 : 0), instead of stepping L times, we will step L-1 times, and our final time will also sever the link between the last node from the previous part and the first node from the next part.
[21]:
class Solution2(object):
"""
Time: O(N + k), where N is the number of nodes in the given list.
If k is large, it could still require creating many new empty lists.
Space: O(k), the additional space used in writing the answer.
"""
def splitListToParts(self, root, k):
cur = root
for N in range(1001):
if not cur: break
cur = cur.next
width, remainder = divmod(N, k)
ans = []
cur = root
for i in range(k):
head = cur
for j in range(width + (i < remainder) - 1):
if cur: cur = cur.next
if cur:
cur.next, cur = None, cur.next
ans.append(head)
return ans
[22]:
s = Solution2()
root = ListNode(1)
root.next = ListNode(2)
root.next.next = ListNode(3)
k = 5
res = s.splitListToParts(root, k)
# print(res) # ['1 -> None', '2 -> None', '3 -> None', None, None]
exp = [1,2,3,None,None]
i = 0
for val in exp:
if val:
assert res[i].val == val
res[i] = res[i].next
i += 1
root = ListNode(1)
root.next = ListNode(2)
root.next.next = ListNode(3)
root.next.next.next = ListNode(3)
root.next.next.next.next = ListNode(4)
root.next.next.next.next.next = ListNode(5)
root.next.next.next.next.next.next = ListNode(6)
root.next.next.next.next.next.next.next = ListNode(7)
root.next.next.next.next.next.next.next.next = ListNode(8)
root.next.next.next.next.next.next.next.next.next = ListNode(9)
root.next.next.next.next.next.next.next.next.next.next = ListNode(10)
k = 3
res = s.splitListToParts(root, k)
# print(res) # ['1 -> 2 -> 3 -> 3 -> None', '4 -> 5 -> 6 -> 7 -> None', '8 -> 9 -> 10 -> None']
exp = [[1,2,3,3], [4,5,6,7], [8,9,10]]
for grp in range(len(exp)):
for val in exp[grp]:
assert res[grp].val == val
res[grp] = res[grp].next